<?php
namespace App\Logic\SalesAmazon;

use App\Models\Amazon\AmazonOrder;
use App\Models\Basics\AmazonCountry;
use App\Models\SalesAmazon\SalesAmountDay;
use Illuminate\Support\Facades\DB;
class SalesAmount2Daily
{
    public static function init()
    {
        $num = 400;
        $i = 161;
        $country = [];
        while(true){
            if($i > $num)break;
            $time = strtotime("-{$i} days");
            $start = date('Y-m-d 00:00:00',$time);
            $end = date('Y-m-d 23:59:59',$time);
            $day = date('Ymd',$time);
            DB::beginTransaction();
            try{
                $currency = [];
                $sku = [];
                SalesAmountDay::query()->where('day',$day)->update(['promotion_discount' => 0]);
                AmazonOrder::query()->where('purchase_date','>=',$start)
                    ->where('purchase_date','<=',$end)
                    ->where('order_status','>=',3)
                    ->where('order_status','<>',7)
                    ->select('id','amazon_order_id','marketplace_id')
                    ->orderBy('id')
                    ->chunk(500, function ($aOrders) use(&$country,&$currency,&$sku,$day,$time){
                        foreach ($aOrders as $aOrder){
                            if(!array_key_exists($aOrder->marketplace_id,$country)){
                                $country[$aOrder->marketplace_id] = AmazonCountry::getCountryIdByMarketplaceId($aOrder->marketplace_id);
                            }
                            $countryId = $country[$aOrder->marketplace_id];
                            foreach ($aOrder->items as $item){
                                if(is_null($item->currency))continue;
                                $amount = SalesAmountDay::query()
                                    ->where('country_id',$countryId)
                                    ->where('seller_sku',$item->sku)
                                    ->where('day',$day)
                                    ->first();
                                if($amount) {
                                    $amount->promotion_discount += ($item->promotion_discount ?: 0);
                                    $amount->save();
                                }
                            }
                        }
                    });
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }
            $i++;
            sleep(10);
        }
    }
}
